import { useEffect, useState } from 'react';
import { Text, View } from '@tarojs/components'
interface TimeLeft {
  days: number;
  hours: number;
  minutes: number;
  seconds: number;
  isEnded: boolean;
  diff: number; // 新增总时间差字段
}

interface CountdownProps {
  targetTimestamp: number;
  className?: string;
  onEnd?: () => void;
  endText?: string;
}

function useCountdown(targetTimestamp: number): TimeLeft {
  const [timeLeft, setTimeLeft] = useState<TimeLeft>(() =>
    calculateTimeLeft(targetTimestamp)
  );

  useEffect(() => {
    if (timeLeft.isEnded) return;

    const interval = setInterval(() => {
      setTimeLeft(calculateTimeLeft(targetTimestamp));
    }, 1000);

    return () => clearInterval(interval);
  }, [targetTimestamp, timeLeft.isEnded]);

  return timeLeft;
}

function calculateTimeLeft(targetTimestamp: number): TimeLeft {
  const diff = targetTimestamp * 1000 - Date.now();

  if (diff <= 0) {
    return {
      days: 0,
      hours: 0,
      minutes: 0,
      seconds: 0,
      isEnded: true,
      diff: 0
    };
  }

  return {
    days: Math.floor(diff / (1000 * 60 * 60 * 24)),
    hours: Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)),
    minutes: Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60)),
    seconds: Math.floor((diff % (1000 * 60)) / 1000),
    isEnded: false,
    diff // 保留总时间差
  };
}

function formatTime(time: TimeLeft) {
  const { diff, days, hours, minutes, seconds } = time;

  // 按时间层级动态显示
  const parts: Array<String> = [];
  if (diff >= 86400000) { // 显示天数及以上
    parts.push(`${days}天`);
    parts.push(`${hours.toString().padStart(2, '0')}小时`);
    parts.push(`${minutes.toString().padStart(2, '0')}分钟`);
  } else if (diff >= 3600000) { // 显示小时及以上
    parts.push(`${hours}小时`);
    parts.push(`${minutes.toString().padStart(2, '0')}分钟`);
  } else if (diff >= 60000) { // 显示分钟及以上
    parts.push(`${minutes}分钟`);
  }

  // 始终显示秒（除非倒计时结束）
  parts.push(`${seconds.toString().padStart(2, '0')}秒`);

  return parts.join(' ');
}

export function Countdown({
  targetTimestamp,

  onEnd,
  endText = '倒计时已结束'
}: CountdownProps) {
  const { isEnded, ...time } = useCountdown(targetTimestamp);

  useEffect(() => {
    if (isEnded && onEnd) onEnd();
  }, [isEnded, onEnd]);

  return (
    <>
      {isEnded ? <View className='bg-#F5F5F5 w-full h-70px px-22px box-border flex items-center text-26px text-#8232E8'>{endText}</View> : <View className='bg-#F5F5F5 w-full h-70px px-22px box-border flex items-center text-26px text-#333333'>
        <Text>请在</Text>
        <View className="px-10px">
          <Text className="text-#8232E8">{formatTime(time)}</Text>
        </View>
        <Text>内接单，超时自动取消</Text>
      </View>}
    </>
    // <>
    // <Text>请在接单</Text>
    // <Text className="text-#FF3A3A">{isEnded ? endText : formatTime(time)}</Text>
    // </>
  );
}